<script lang="ts">
export default {
  name: "OperateMonitorTaskEditDialog"
}
</script>

<!--
 * @Descripttion: 编辑对话框
 * @version:
 * @Author: hupengwu
 * @Date: 2022-10-24 09:10:28
 * @LastEditors: hupengwu
 * @LastEditTime: 2022-10-24 09:10:28
-->
<template>
  <!-- 对话框 -->
  <el-dialog :close-on-click-modal="false" :model-value="visible" :title="dataState.title" min-width="200px"
             @close="handleCancel">

    <!-- 数据表单 -->
    <el-form ref="dataFormRef" :model="dataState.formData" :rules="dataState.rules" label-width="100px">

      <!-- 编辑框：配置名称 -->
      <el-form-item label="模板名称" prop="templateName">
        <el-input v-model="dataState.formData.templateName" :disabled="dataState.type==='update'"/>
      </el-form-item>

      <!-- 下拉框：设备类型 -->
      <el-form-item label="设备厂商" prop="manufacturer">
        <el-select v-model="dataState.formData.manufacturer" placeholder="请选择"
                   @change="handleSelectManufacturer">
          <el-option
            v-for="item in dataState.manufacturerOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>

        <el-form-item label="设备类型" prop="deviceType">
          <el-select v-model="dataState.formData.deviceType" placeholder="请选择">
            <el-option
              v-for="item in dataState.deviceTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form-item>

      <el-form-item label="采样周期" prop="timeUnit">
        <el-select v-model="dataState.timeUnit" placeholder="请选择">
          <el-option
            v-for="item in dataState.timeTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>

        <el-form-item label="采样间隔" prop="timeInterval">
          <el-input v-model="dataState.timeInterval" :autosize="{ minRows: 1, maxRows: 100 }" type="textarea"/>
        </el-form-item>
      </el-form-item>

      <!-- 下拉框：配置参数 -->
      <el-form-item label="模板参数" prop="templateParamJson">
        <el-input v-model="dataState.formData.templateParamJson" :autosize="{ minRows: 1, maxRows: 100 }" type="textarea"/>
      </el-form-item>
    </el-form>

    <!-- 脚部：确认/取消按钮-->
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
        <el-button @click="handleCancel">取 消</el-button>
      </div>
    </template>

  </el-dialog>
</template>

<script lang="ts" setup>
import {onMounted, reactive, ref} from "vue";

import {ElForm, ElMessage} from "element-plus";
import {
  OperateMonitorTaskItem,
  CreateOperateMonitorTaskRequestVO
} from "@/api/device/operate/task/monitor/types";
import {listOption2List, listOptionList} from "@/api/option";

const props = defineProps(['visible']);
const emit = defineEmits(['create', 'update', 'cancel']); //注意：这个是父组件<dict-type-edit>标签上的@close
const dataFormRef = ref(ElForm); // 属性名必须和元素的ref属性值一致

/**
 * 对外声明接口：父页面可以调用它
 */
defineExpose({initEditData});

// 数据状态：定义
let dataState = reactive({
  // 类型：create/update
  type: 'create',
  // 标题
  title: '添加模板',
  // 表单数据
  formData: {
    id: undefined,
    deviceType: '',
    manufacturer: '',
    templateName: '',
    templateParam: [],
    templateParamJson: '[]',
    deviceIds: [] as number[],
    taskParam: {},
  } as CreateOperateMonitorTaskRequestVO,

  timeMode: 'interval',
  timeUnit: 'second',
  timeInterval: "1",

  // 厂商类型选项
  manufacturerOptions: [] as OptionType[],
  // 配置类型选项
  deviceTypeOptions: [] as OptionType[],
  // 配置类型选项
  timeTypeOptions: [] as OptionType[],

  // 对话框的各控件输入规则
  rules: {
    templateName: [{required: true, message: '参数不能为空', trigger: 'blur'}],
    deviceType: [{required: true, message: '参数不能为空', trigger: 'blur'}],
    manufacturer: [{required: true, message: '参数不能为空', trigger: 'blur'}],
    templateParamJson: [{required: true, message: '参数不能为空', trigger: 'blur'}],
    timeUnit: [{required: true, message: '参数不能为空', trigger: 'blur'}],
  },
});

/**
 * 设备类型下拉框
 * @taskParam value
 */
async function handleSelectManufacturer(value: any) {
  await listOption2List("OperateEntity", "manufacturer", value, 'deviceType').then(({data}) => {
    dataState.deviceTypeOptions = data;
    if (dataState.deviceTypeOptions.length > 0){
      dataState.formData.deviceType = dataState.deviceTypeOptions[0].value;
    }
  });
}

/**
 * 取消
 */
function handleCancel() {
  //执行调用<operateTemplate-edit-dialog @cancel="cancelEdit">
  emit('cancel', "子组件传给父组件的值");
}

/**
 * 确认：新增/修改实体
 */
function handleSubmit() {
  if (dataState.formData.templateName === '') {
    ElMessage.info('名称不能为空');
    return;
  }

  if (dataState.timeMode === '' || dataState.timeUnit === '' || dataState.timeInterval === '') {
    ElMessage.info('采样参数格式不正确');
    return;
  }
  else {
    dataState.formData.taskParam.timeMode = dataState.timeMode;
    dataState.formData.taskParam.timeUnit = dataState.timeUnit;
    dataState.formData.taskParam.timeInterval = Number.parseInt(dataState.timeInterval);
  }

  if (!dataState.formData.templateParamJson?.startsWith('[') || !dataState.formData.templateParamJson?.endsWith(']')) {
    ElMessage.info('配置参数的格式，不是合法的JSON数组格式!');
    return;
  }

  try {
    dataState.formData.templateParam = JSON.parse(dataState.formData.templateParamJson as string);
  } catch (e) {
    ElMessage.info('配置参数的格式，不是合法的JSON格式!');
    return;
  }

  if (dataState.type === 'create') {
    emit('create', dataState.formData);
  }
  if (dataState.type === 'update') {
    emit('update', dataState.formData);
  }
}

/**
 * 初始化对话框
 * @taskParam type 对话框类型
 * @taskParam entity 实体
 */
function initEditData(type: string, entity: OperateMonitorTaskItem) {
  if (entity !== undefined) {
    dataState.formData.templateName = entity.templateName;
    dataState.formData.deviceType = entity.deviceType;
    dataState.formData.manufacturer = entity.manufacturer;
    dataState.formData.templateParam = entity.templateParam;
    dataState.formData.templateParamJson = JSON.stringify(entity.templateParam, null, 5);
    dataState.formData.deviceIds = entity.deviceIds;
    dataState.formData.deviceIdsJson = JSON.stringify(entity.deviceIds, null, 5);

    dataState.formData.taskParam = entity.taskParam;
    dataState.timeMode = entity.taskParam.timeMode;
    dataState.timeUnit = entity.taskParam.timeUnit;
    dataState.timeInterval = entity.taskParam.timeInterval;

    if (entity.manufacturer !== undefined) {
      listOption2List("OperateEntity", "manufacturer", entity.manufacturer as string, 'deviceType').then(({data}) => {
        dataState.deviceTypeOptions = data;
      });
    }
  }

  if (type === 'create') {
    dataState.type = type;
    dataState.title = '新增配置';

    dataState.formData.id = undefined;

    return;
  }

  if (type === 'update') {
    dataState.type = type;
    dataState.title = '修改配置';

    dataState.formData.id = entity.id;

    return;
  }
}

/**
 * 响应页面安装：页面的初始化工作
 */
onMounted(() => {
  // 设备厂商/设备类型，两级初始化
  listOptionList("OperateEntity", "manufacturer").then(async ({data}) => {
    dataState.manufacturerOptions = data;
  });

  dataState.timeTypeOptions.push({value: 'second', label: '秒'});
  dataState.timeTypeOptions.push({value: 'minute', label: '分'});
  dataState.timeTypeOptions.push({value: 'hour', label: '时'});
  dataState.timeTypeOptions.push({value: 'day', label: '天'});
});

</script>
